package spring.boot.btc.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

@Slf4j
@Service
public class BlockReceiveService {

    @Autowired
    private BlockMsgHandlerService blockMsgHandlerService;

    public void receive() {
        byte[] data = new byte[16384];
        MulticastSocket ms = null;
        try {
            InetAddress ip = InetAddress.getByName(BlockSenderService.HOST);
            ms = new MulticastSocket(BlockSenderService.PORT);
            ms.joinGroup(ip);
            DatagramPacket packet = new DatagramPacket(data, data.length);
            //receive()是阻塞方法，会等待客户端发送过来的信息
            ms.receive(packet);
            String message = new String(packet.getData(), 0, packet.getLength());
            blockMsgHandlerService.doHandlerMsg(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ms != null) {
                ms.close();
            }
        }
    }

    public void receiveMoney() {
        byte[] data = new byte[16384];
        MulticastSocket ms = null;
        try {
            InetAddress ip = InetAddress.getByName(BlockSenderService.HOST);
            ms = new MulticastSocket(BlockSenderService.PORT);
            ms.joinGroup(ip);
            DatagramPacket packet = new DatagramPacket(data, data.length);
            //receive()是阻塞方法，会等待客户端发送过来的信息
            ms.receive(packet);
            String message = new String(packet.getData(), 0, packet.getLength());
            blockMsgHandlerService.doHandlerMsg(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ms != null) {
                ms.close();
            }
        }
    }

}
